﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Task_When_GetAsyncState.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Defines the Task_When_GetAsyncState type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Threading
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Mocks;
    using Testing.Threading;

    [TestClass]
    public class Task_When_GetAsyncState : AsynchronousTest
    {
        [TestMethod]
        [HostType("CHESS")]
        public void If_Started_With_AsyncState_Should_Return_Supplied_State()
        {
            var result = TestStrings.Timeout;
            var task = Task.Factory.From(MockDelegates.DoNothing);
            task.Start(t =>
                {
                    // verify the value is available in the callback
                    result = (string)t.AsyncState;
                    if (result != TestStrings.Success)
                        result = TestStrings.Failure;
                }, TestStrings.Success);

            // verify value is available after calling start
            Assert.AreEqual(task.AsyncState, TestStrings.Success);

            // wait for completion to check value in callback
            AsyncUtility.SleepUntil(() => result != TestStrings.Timeout);
            Assert.AreEqual(result, TestStrings.Success);
        }

        [TestMethod]
        [HostType("CHESS")]
        public void If_ContinuingFrom_With_AsyncState_Should_Return_Supplied_State()
        {
            var asyncStateInCallback = TestStrings.Timeout;

            var continuationSource = new MockContinuationSource();

            // initialize task
            var task = Task.Factory.From(MockDelegates.DoNothing);
            task.ContinueFrom(continuationSource, t =>
                {
                    // read AsyncState in callback
                    asyncStateInCallback = (string)t.AsyncState;
                    if (asyncStateInCallback != TestStrings.Success)
                        asyncStateInCallback = TestStrings.Failure;
                }, TestStrings.Success);
            Assert.AreEqual(task.AsyncState, TestStrings.Success);

            // set complete
            continuationSource.Completed();
            Assert.AreEqual(task.AsyncState, TestStrings.Success);

            // wait for completion to check value in callback
            AsyncUtility.SleepUntil(() => asyncStateInCallback != TestStrings.Timeout);
            Assert.AreEqual(asyncStateInCallback, TestStrings.Success);
        }
    }
}
